<template>
	<div>
		<div class="container">
			<div class="toolbar">
				<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
					<a-row :gutter="20">
						<a-col :span="24">
							<a-form-item label="选择签收状态">
								<a-radio-group v-model:value="searchState.receive_status" @change="initData">
									<a-radio-button v-for="option of statusOptions" :key="option.value" :value="option.value">{{ option.label }}</a-radio-button>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>
					<a-row :gutter="20">
						<a-col :span="8">
							<a-form-item label="选择项目" style="width:250px">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择项目" :options="projectlist" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item label="收料人" style="width:250px">
								<a-input v-model:value="searchState.receiver_name" placeholder="请输入收料人名称"></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="8">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
        v-if="!loading"使得:default-expand-all-rows="true"生效
        -->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" row-key="id" children-column-name="children" :default-expand-all-rows="false" :data-source="acceptSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'operation'">
							<a-space>
								<a-button v-permission="209" type="link" @click="showUselog(record)">
									<right-outlined />查看
								</a-button>
								<a-button v-if="record.receive_status === 1 && record.receiver_id === userInfo.id" v-permission="210" type="link" @click="sign(record)">
									<right-outlined />签收
								</a-button>
								<!--
                <a-button type="link" @click="editUselog(record)">
                  <edit-outlined />修改
                </a-button>
                <a-button type="link" style="color:#ff7875" @click="deleteUselog(record.id)">
                  <delete-outlined />删除
                </a-button>
                -->
							</a-space>
						</template>
						<template v-else-if="column.key === 'flowStatus'">
							<div>
								<flow-model :module-id="'planjx'" :item-id="record.id" @change="changeFlowStatusData2"></flow-model>
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const projectlist = ref([]);
const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";
import { userStore } from "@/store/index.js";
const store = userStore();
const userInfo = store.info;
const route = useRoute();
const router = useRouter();
const query = route.query;
const searchRef = ref();
const searchState = reactive({
	receive_status: ''
});
const statusOptions = [
	{
		value: "",
		label: "全部"
	},
	{
		value: "1",
		label: "待收料"
	},
	{
		value: "2",
		label: "已收料"
	}
];
post("department/projects", { type: 3, get_type: 1, is_effective: true }).then(({ data }) => {
	projectlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "项目名称",
		fixed: "left",
		dataIndex: "project",
		sorter: false,
		width: 200,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.name;
		}
	},
	{
		title: "工号",
		dataIndex: "gonghao",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text?.name;
		}
	},
	{
		title: "发料人",
		dataIndex: "user",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return text.fullname;
		}
	},
	{
		title: "物料接收人",
		dataIndex: "receiver",
		sorter: false,
		width: 240,
		align: "center",
		ellipsis: true
	},
	{
		title: "发料日期",
		dataIndex: "create_time",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			//未设置dataIndex，text和record返回值相同
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "签收状态",
		dataIndex: "receive_status",
		sorter: false,
		width: 100,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text === 1 ? "待收料" : "已收料";
		}
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 150,
		align: "center"
	}
];
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));
const changeflowStatus = e => {
	if (e && searchState) {
		searchState.ids = e.ids;
		if (searchState.ids) {
			initData();
		}
	}
};
const { data, loading, run, current, pageSize, total } = usePagination(params => {
	const search = { ...params, ...searchState };
	if (userInfo.is_supplier === 1) {
		search.opr_type = 1;
	} else if (userInfo.is_consignor === 1) {
		search.receiver_id = userInfo.id;
	}
	return post("uselog", search)
}, {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const acceptSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		//格式化接收人
		if (d.opr_type === 1) {
			if (d?.client?.name) {
				d.receiver = `${d?.client?.name}（${d?.supplier?.company_name}）`;
			} else {
				d.receiver = `${d?.receiver?.fullname}（${d?.supplier?.company_name}）`;
			}
		} else {
			d.receiver = d?.receiver?.fullname;
		}
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

if (query) {
	if (query.receive_status) searchState.receive_status = query.receive_status;
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	if (query.receiver_name) searchState.receiver_name = query.receiver_name;
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

const showUselog = ({ id }) => {
	router.push(`/uselogSign/info/${id}`);
};
const sign = ({ id }) => {
	router.push(`/uselogSign/edit/${id}`);
};
const deleteUselog = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的申请记录吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("uselog/delete", { id }).then(() => {
				proxy.$message.success("记录删除成功");
				initData();
			});
		}
	});
};
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
</style>